<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/6
 * Time: 14:05
 */

namespace common\models\Service;


use common\models\Cache;
use common\models\CommonFunction;
use common\models\DAO\DayAccrual;
use common\models\DAO\ProductList;
use common\models\DAO\TeamBrokerage;
use common\models\DAO\User;
use common\models\DAO\UserCoupon;
use common\models\DAO\UserCouponUseList;
use common\models\DAO\UserHongbao;
use common\models\DAO\UserHongbaoUseList;
use common\models\DAO\UserInvest;
use common\models\DAO\UserWalletLog;
use common\models\Http;
use common\msg\UserMsg;
use common\models\DAO\Product;

class ProductService {

    public static function setting($id){
        $setting = DayService::get($id);

        $setting['rate'] = CommonFunction::formatMoney($setting['rate']);

        $result['setting'] = $setting;
        return $result;
    }

    public static function day($id = 1, $userID = 0){
        $setting = DayService::get($id);

        $setting['rate'] = CommonFunction::formatMoney($setting['rate']);

        $result['setting'] = $setting;
        $least_invest = \Yii::$app->params['least_invest'];
        $result['least_invest'] = $least_invest / 100;
        $result['init_money'] = $least_invest;
        if($id > 1){
            $hb_scale = HongBaoService::setting($setting['day']);
            $result['init_hongbao'] = intval($least_invest/$hb_scale);
        }
        if(!empty($userID)){
            $remainder = Wallet::remainder($userID);
            $user['remainder'] = $remainder;
            if($remainder > 0)
                $result['init_money'] = $remainder;
            if($id > 1){
                $result['coupon'] = CouponService::one($userID);
                $hongbao = HongBaoService::get($userID);
                $user['hongbao'] = $hongbao;
                $user['hb_scale'] = $hb_scale;
                $result['init_hongbao'] = intval($least_invest/$user['hb_scale']);

                if($remainder > 0){
                    $result['init_hongbao'] = intval($remainder/$user['hb_scale']);
                }
                if($result['init_hongbao'] > $hongbao)
                    $result['init_hongbao'] = $hongbao;
            }
            $result['user'] = $user;
        }
        return $result;
    }

    /*
    * 投标动作
    */
    public static function complete($param, $sourceID = 1){
        $result['status'] = 0;
        $result['msg'] = UserMsg::$time_out;
		if(!isset($param['id']))
            return $result;
        //标的基础信息
        $investInfo = Product::findOne($param['id']);
        if(!$investInfo)
            return $result;
        $investID = $param['id'];
        $now = time();
        $userID = $param['userID'];
        $remainder = Wallet::remainder($userID);
        $money = intval(floatval($param['money']) * 100);
        $coupon = 0;
        $hongbao = 0;
        $day = $investInfo['day'];
        $least_invest = \Yii::$app->params['least_invest'];

        if($money < intval($least_invest)){
            $result['msg'] = '投资金额不能少于'.$least_invest/100 . '元!';
            return $result;
        }
        if($money > $remainder ){
            $result['msg'] = UserMsg::$no_money;
            return $result;
        }



        if(isset($param['hongbao'])){
            $hongbao_day = $day;
            if($day < 30)
                $hongbao_day = 30;
            $hb_scale = HongBaoService::setting($hongbao_day);
            $hongbao = floatval($param['hongbao']) * 100;
            $can_use_hongbao = $money / $hb_scale;
            if($can_use_hongbao < $hongbao){
                $result['msg'] = '本次投资，现金红包最大可使用' . CommonFunction::formatWan($can_use_hongbao) . '元。';
                return $result;
            }
            $user_hongbao = 0;
            $user_hongbao_model = UserHongbao::findOne($userID);
            $user_hongbao_model && $user_hongbao = $user_hongbao_model['money'];
            if($hongbao > $user_hongbao){
                $result['msg'] = UserMsg::$no_hongbao;
                return $result;
            }
        }
        $couponID = 0;
        if(isset($param['couponID'])){
            $couponID = intval($param['couponID']);
            $coupon_model = UserCoupon::findOne(['id'=>$couponID, 'userID'=>$userID, 'status'=>0]);
            if(!$coupon_model || date('Ymd') >= $coupon_model['loseTime']){
                $result['msg'] = UserMsg::$no_coupon;
                return $result;
            }
            $coupon = $coupon_model['card'];
        }
        $is_invest = 0;
        if(!empty($param['recID'])){
            $is_invest = UserInvest::find()->where(['userID'=>$userID])->andWhere('productID!=0')->count();
        }

        $transaction = \Yii::$app->db->beginTransaction();


        //更新用户投资列表
        $rate = $investInfo['rate'];
        $start_date =  date("Ymd",strtotime("+1 day"));
        $over_day = $day + 1;
        $end_date =  date("Ymd",strtotime("+$over_day day"));
        $system_day = \Yii::$app->params['system_day'];
        $accrual = intval(($money + $hongbao) * ($rate + $coupon) * $day / $system_day / 10000);
        $userInvest = new UserInvest();
        $userInvest->userID = $userID;
        $userInvest->productID = $investID;
        $userInvest->title = $investInfo['name'];
        $userInvest->startTime = $start_date;
        $userInvest->endTime = $end_date;
        $userInvest->money = $money + $hongbao;
        $userInvest->accrual = $accrual;
        $userInvest->typeID = 2;
        $userInvest->createTime = $now;
        $userInvest->sourceID = $sourceID;
        $userInvest->rate = $rate + $coupon;
        $userInvest->hongBao = $hongbao;
        $userInvest->couponID = $couponID;
        $userInvest->coupon = $coupon;

        $userInvest_result = $userInvest->save();
        if(!$userInvest_result){
            $transaction->rollBack();
            return $result;
        }

        $userInvestID = $userInvest->id;

        //公共参数
        $pub_param['userID'] = $userID;
        $pub_param['investID'] = $investID;

        //更新用户余额 - 扣除账户余额
        $accrual_param = $pub_param;
        $accrual_param['userInvestID'] = $userInvestID;
        $accrual_param['money'] = $money;
        $accrual_param['createTime'] = $now;
        $accrual_param['productID'] = $investID;
        $accrual_param['investID'] = 0;
        $accrual_param['wallet_type'] = 2;
        $accrual_param['wallet_road'] = 4;
        $accrual_result = Wallet::deduct($accrual_param, 'desc');
        if(!$accrual_result){
            $transaction->rollBack();
            return $result;
        }
        $isNew = $param['isNew'];
        //分销系统
        if(!empty($param['recID'])){
            if($is_invest == 0 && $money >= 100000 && $now < strtotime('20160316')){
                $invite_money = 5000;
                $date = date('Ymd');
                $dayAccrual = new DayAccrual();
                $dayAccrual->userID = $param['recID'];
                $dayAccrual->date = $date;
                $dayAccrual->money = $invite_money;
                $dayAccrual->invest = $invite_money;
                $dayAccrual->createTime = $now;
                $dayAccrual->updateTime = $now;
                $dayAccrual->typeID = 18;
                $dayAccrual->gmID = $userInvestID;
                $accrual_result  = $dayAccrual->save();
                if(!$accrual_result){
                    $transaction->rollBack();
                    return $result;
                }
                //钱包明细
                $user_wallet = new UserWalletLog();
                $user_wallet->type = 1;
                $user_wallet->money = $invite_money;
                $user_wallet->createTime = $now;
                $user_wallet->userID = $param['recID'];
                $user_wallet->road = 18;
                $user_wallet->gmID = $userInvestID;
                $user_wallet->desc = '邀请好友投资奖励';
                $user_wallet_result = $user_wallet->save();
                if(!$user_wallet_result) {
                    $transaction->rollBack();
                    return $result;
                }

                $team_brokerage = new TeamBrokerage();
                $team_brokerage->investID = $userInvestID;
                $team_brokerage->productID = $investID;
                $team_brokerage->userID = $param['recID'];
                $team_brokerage->investUserID = $userID;
                $team_brokerage->money = $money;
                $team_brokerage->day = $day;
                $team_brokerage->brokerage = $invite_money;
                $team_brokerage->createTime = $now;
                $team_brokerage->userInvestID = $userInvestID;
                $brokerage_result = $team_brokerage->save();
                if(!$brokerage_result) {
                    $transaction->rollBack();
                    return $result;
                }
                if(!empty($param['openID'])){
                    SendWxMessage::charge($param['openID'], CommonFunction::formatMoney($invite_money), '恭喜您，邀请的好友已成功投资生财有道365定期产品，您已获得50元现金奖励。');
                }
            }
            $team_patam['tel'] = $param['tel'];
            $team_patam['userID'] = $userID;
            $team_patam['money'] = $money + $hongbao;
            $team_patam['day'] = $day;
            $team_patam['recID'] = $param['recID'];
            $team_patam['investID'] = 0;
            $team_patam['productID'] = $investID;
            $team_patam['userInvestID'] = $userInvestID;
            $team_result = TeamService::insert($team_patam);
            if(!$team_result){
                $transaction->rollBack();
                return $result;
            }
        }
        if($money >= 1000000 && $day == 25){
            $card = 20;
            $money >= 3000000 && $card = 50;
            $money >= 5000000 && $card = 100;
            $user_coupon = new UserCoupon();
            $user_coupon->userID = $userID;
            $user_coupon->createTime = $now;
            $user_coupon->card = $card;
            $lose_day = 31 + 1;
            $user_coupon->loseTime = date('Ymd', strtotime("+$lose_day day"));
            $user_coupon_result = $user_coupon->save();
            if(!$user_coupon_result){
                $transaction->rollBack();
                return $result;
            }
        }
        //投资记录
        $investList = new ProductList();
        $investList->userID = $userID;
        $investList->money = $money;
        $investList->hongBao = $hongbao;
        $investList->accrual = $accrual;
        $investList->coupon = $coupon;
        $investList->couponID = $couponID;
        $investList->rate = $rate + $coupon;
        $investList->createTime = $now;
        $investList->startTime = $start_date;
        $investList->endTime = $end_date;
        $investList->sourceID = $sourceID;
        $investList->productID = $investID;
        $investList_result = $investList->save();
        if(!$investList_result){
            $transaction->rollBack();
            return $result;
        }

        //更新红包状态
        if($hongbao > 0 && isset($user_hongbao_model) && !empty($user_hongbao)){
            $user_hongbao_model->money = $user_hongbao - $hongbao;
            $hb_result = $user_hongbao_model->save();
            if(!$hb_result){
                $transaction->rollBack();
                return $result;
            }
            $hb_use = new UserHongbaoUseList();
            $hb_use->userID = $userID;
            $hb_use->hongBao = $hongbao;
            $hb_use->createTime = $now;
            $hb_use->userInvestID = $userInvestID;
            $hb_use->investID = $investID;
            $hb_use->type = 1;
            $hb_use_result = $hb_use->save();
            if(!$hb_use_result){
                $transaction->rollBack();
                return $result;
            }

        }
        //更新年利卷状态
        if($couponID > 0 && $coupon > 0 && isset($coupon_model)){
            $coupon_model->status = 1;
            $coupon_result = $coupon_model->save();
            if(!$coupon_result){
                $transaction->rollBack();
                return $result;
            }
            $coupon_use_model = new UserCouponUseList();
            $coupon_use_model->userID = $userID;
            $coupon_use_model->useTime = $now;
            $coupon_use_model->card = $coupon;
            $coupon_use_model->userInvestID = $userInvestID;
            $coupon_use_model->productID = $investID;
            $coupon_use_model->couponID = $couponID;
            $coupon_use_result = $coupon_use_model->save();
            if(!$coupon_use_result){
                $transaction->rollBack();
                return $result;
            }
        }

        //用户日志
        $user_log = UserLog::set(['userID'=>$userID, 'money'=> $money + $hongbao, 'hongBao'=> $hongbao, 'rate'=>$rate + $coupon, 'coupon'=>$coupon,
            'productID'=>$investID, 'sourceID'=>$sourceID, 'desc'=>'投资'.$investInfo['name']]);
        if(!$user_log){
            $transaction->rollBack();
            return $result;
        }

        $user_integral_param = $pub_param;
        $user_integral_param['userInvestID'] = $userInvestID;
        $user_integral_param['day'] = $day;
        $user_integral_param['money'] = $money + $hongbao;
        $user_integral_param['createTime'] = $now;
        $user_integral_param['desc'] = '投资【'.$investInfo['name'].'】';
        $user_integral_param['investID'] = 0;
        $user_integral_param['productID'] = $investID;
        $user_integral_result = IntegralService::add($user_integral_param);
        if(!$user_integral_result){
            $transaction->rollBack();
            return $result;
        }
        $investInfo->money = $investInfo['money'] + $money + $hongbao;
        $investInfo->person = $investInfo['person'] + 1;
        $invset_result = $investInfo->save();
        if(!$invset_result){
            $transaction->rollBack();
            return $result;
        }else{
            $action_start = strtotime('20160214');
            $action_end = strtotime('20160218');
            if($now >= $action_start && $now < $action_end){

                //投资返基金投资
                $_day = 8;
                $_rate = 1100;
                $over_day = 9;
                $_investModel = new UserInvest();
                $_investModel->userID = $userID;
                $_investModel->investID = 0;
                $_investModel->title = '浪漫情人节标';
                $_investModel->startTime = $start_date;
                $_investModel->endTime = date("Ymd",strtotime("+$over_day day"));
                $_investModel->money = 0;
                $_investModel->accrual = intval($money * $_rate * $_day / $system_day / 10000);
                $_investModel->status = 1;
                $_investModel->createTime = $now;
                $_investModel->sourceID = $sourceID;
                $_investModel->rate = $_rate;
                $_investModel->FundID = 2;
                $invest_result = $_investModel->save();
                $fund_money = CommonFunction::formatMoney($money);
                $remark = "恭喜您已投资成功,明日开始计息。特奖励您情人节专属基金红包{$fund_money}元，系统会帮您将所得基金红包自动参与到浪漫情人节标。您可点击”投资管理“，查看详情。";
                if(!$invest_result){
                    $transaction->rollBack();
                    return $result;
                }
            }
			if(!empty($param['openID'])){
                $send_param = ['openID'=>$param['openID'],'name'=>$investInfo['name'],
                    'rate'=> CommonFunction::formatMoney($rate + $coupon).'%',
                    'day'=>$day.'天',
                    'money'=>CommonFunction::formatMoney($money + $hongbao).'元',
                    'accrual'=>CommonFunction::formatMoney($accrual).'元',
                    'id'=>$userInvestID
                ];
                isset($remark) && $send_param['remark'] = $remark;
                SendWxMessage::invest($send_param);
            }
            $transaction->commit();
        }

        $cache_name = 'product_'.$investID;
        $cache = Cache::get($cache_name);
        if($cache){
            $cache['money'] = $investInfo['money'];
            $cache['person'] = $investInfo['person'];
            Cache::set($cache_name, $cache);
        }

        if($isNew == 1){
            $userModel = User::findOne($userID);
            $userModel->isNew = 0;
            $userModel->save();
            $userInfo = Http::session('user');
            $userInfo['isNew'] = 0;
            Http::session('user', $userInfo);
        }
        return ['status'=>1, 'url'=> \Yii::$app->urlManager->createUrl(['invest/index', 'id' => $userInvestID]),'id' => $userInvestID];
    }
}